<template>
  <div class="keep-alive-demo">
    <h1>Keep-Alive 示例</h1>

    <div class="demo-section">
      <h2>组件状态保持</h2>
      <p>切换下面的组件，观察计数器的状态是否被保持</p>

      <div class="controls">
        <button @click="currentComponent = components.CounterA">显示计数器 A</button>
        <button @click="currentComponent = components.CounterB">显示计数器 B</button>
        <button @click="currentComponent = components.CounterC">显示计数器 C</button>
      </div>

      <div class="component-container">
        <!-- 使用 keep-alive 包裹动态组件 -->
        <keep-alive>
          <component :is="currentComponent" />
        </keep-alive>
      </div>
    </div>

    <div class="demo-section">
      <h2>不使用 Keep-Alive 对比</h2>
      <p>切换下面的组件，观察计数器的状态是否被重置</p>

      <div class="controls">
        <button @click="currentComponentNoCache = components.CounterA">显示计数器 A</button>
        <button @click="currentComponentNoCache = components.CounterB">显示计数器 B</button>
        <button @click="currentComponentNoCache = components.CounterC">显示计数器 C</button>
      </div>

      <div class="component-container">
        <!-- 不使用 keep-alive -->
        <component :is="currentComponentNoCache" />
      </div>
    </div>

    <div class="info-section">
      <h3>Keep-Alive 的作用</h3>
      <ul>
        <li>✅ 保持组件状态（如计数器、表单数据等）</li>
        <li>✅ 避免重复渲染，提高性能</li>
        <li>✅ 缓存组件实例</li>
        <li>❌ 不使用 keep-alive 时，组件每次都会重新创建</li>
      </ul>
    </div>
  </div>
</template>

<script setup>
import { ref, shallowRef } from 'vue'
import CounterA from '@/components/CounterA.vue'
import CounterB from '@/components/CounterB.vue'
import CounterC from '@/components/CounterC.vue'

// 组件映射
const components = {
  CounterA,
  CounterB,
  CounterC
}

// 使用 keep-alive 的组件
const currentComponent = shallowRef(components.CounterA)

// 不使用 keep-alive 的组件
const currentComponentNoCache = shallowRef(components.CounterA)
</script>

<style scoped>
.keep-alive-demo {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.demo-section {
  margin-bottom: 40px;
  padding: 20px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  background-color: #f9f9f9;
}

.demo-section h2 {
  color: #2c3e50;
  margin-bottom: 15px;
  border-bottom: 2px solid #42b983;
  padding-bottom: 5px;
}

.controls {
  margin-bottom: 20px;
}

.controls button {
  margin: 0 10px 10px 0;
  padding: 8px 16px;
  background-color: #42b983;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.3s;
}

.controls button:hover {
  background-color: #369870;
}

.component-container {
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  border: 1px solid #ddd;
  min-height: 150px;
}

.info-section {
  padding: 20px;
  background-color: #e8f5e8;
  border-radius: 8px;
  border: 1px solid #42b983;
}

.info-section h3 {
  color: #2c3e50;
  margin-bottom: 15px;
}

.info-section ul {
  list-style-type: none;
  padding: 0;
}

.info-section li {
  padding: 5px 0;
  font-size: 14px;
}
</style>
